package 反射6;

import org.apache.commons.beanutils.BeanUtils;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Date:2025/3/18
 * 自己封装的数据库操作类，可以实现增删查改
 * api：
 * getConn(),return Connection,返回数据库连接对象
 * getPreparedStatement(数据库连接对象,sql语句,替换？的可变参数),return PreparedStatement,返回预编译对象
 * release(数据库连接对象,预编译对象,结果集),return void,释放资源
 * update(String sql,Object...parameter),return int,实现增删改操作，返回操作int条数据，参考形式：insert into 表名 values(？,?)
 * queryBean(sql,反射 类的对象，可变参数替换？)，return T一个实例化对象，类型不知道用泛型，用于将数据封装成一个javabean，返回这个实例化对象
 * queryBeanList(sql,反射类对象，可变参数)，return 集合，将数据封装成javabean然后用集合的方式存储
 * queryMap(sql.可变参数)，return map,将数据封装在map中，可以打印出键值对形式的数据
 * queryMapList(sql.可变参数)，return Object[]数组，将数据封装在数组中
 * queryMapList(sql.可变参数),return arraylist,将数据封装在数组中，以集合形式存储
 */
public class MyHandleDbReflection {
    private static String user;
    private static String password;
    private static String driver;
    private static String url;

    /**
     * 驱动,获取配置文件中的参数
     */
    static {
        try {
            InputStream rerceAsStreamsou = MyHandleDbReflection.class.getClassLoader().getResourceAsStream("反射6\\resourse.properties");
            Properties properties = new Properties();
            properties.load(rerceAsStreamsou);
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接数据库
     * @return
     * @throws SQLException
     */
    public static Connection getConn() throws SQLException {
            return DriverManager.getConnection(url,user,password);
    }

    /**
     * 插入数据  可以实现增删改
     * @param sql
     * @param parameter
     * @return
     * @throws SQLException
     */
    public static int update(String sql,Object...parameter) throws SQLException {
        try {
            Connection conn = getConn();
            PreparedStatement preparedStatement = getPreparedStatement(conn,sql,parameter);
            int i = preparedStatement.executeUpdate();
            release(conn,preparedStatement,null);
            return i;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 释放资源
     * @param connection
     * @param preparedStatement
     * @throws SQLException
     * 资源释放的顺序和创建的顺序相反：避免资源依赖问题
     */
    public static void release(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet) throws SQLException {
        if(connection!=null){
            connection.close();
        }
        if(preparedStatement!=null){
            preparedStatement.close();
        }
        if(resultSet!=null){
            resultSet.close();
        }
    }

    /**
     * 获取预编译对象
     * @param sql
     * @param parameter
     * @return
     */
    public static PreparedStatement getPreparedStatement(Connection conn,String sql,Object...parameter){
        PreparedStatement preparedStatement=null;
        try {
            preparedStatement = conn.prepareStatement(sql);
            ParameterMetaData parameterMetaData = preparedStatement.getParameterMetaData();
            int count = parameterMetaData.getParameterCount();
            if(count!=0){
                for (int i = 0; i < count; i++) {
    //第一个参数是表，表从1开始，第二个是可变参数数组，数组从零开始，参数通过传参进来然后set设置给表
                    preparedStatement.setObject(i+1,parameter[i]);
                }
            }
//            release(conn,null);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return preparedStatement;
    }

    /**
     * 利用条件获得1个对象:用id拉出来一条数据
     * @param sql
     * @param c
     * @param parameter
     * @param <T>
     * @return
     */
    public static <T> T queryBean(String sql,Class<T> c,Object...parameter){
//        1.定义需要的对象
        Connection conn=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet;
        T t=null;
//        2.连接数据库
        try {
            conn = getConn();
            preparedStatement = getPreparedStatement(conn,sql, parameter);
            resultSet = preparedStatement.executeQuery();
            resultSet.next();
            ResultSetMetaData metaData = resultSet.getMetaData();
            t = c.newInstance();
            int count = metaData.getColumnCount();
            for (int i = 1; i <= count; i++) {
                //使用导入的jar包中的api
                BeanUtils.setProperty(t,metaData.getColumnName(i),resultSet.getObject(i));
            }
            release(conn,preparedStatement,resultSet);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

        return t;
    }

    /**
     * 利用条件获得多个对象
     * @param sql
     * @param c
     * @param parameter
     * @param <T>
     * @return
     */
    public static <T> ArrayList<T> queryBeanList(String sql,Class<T> c,Object...parameter){
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        T t=null;
        ArrayList<T> arrayList = new ArrayList<>();

        try {
            connection = getConn();
            preparedStatement = getPreparedStatement(connection,sql,parameter);
            ResultSet resultSet = preparedStatement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int count = metaData.getColumnCount();
            while (resultSet.next()){
                t = c.newInstance();
                for (int i = 1; i <= count; i++) {
                    BeanUtils.setProperty(t,metaData.getColumnName(i),resultSet.getObject(i));
                }
                arrayList.add(t);
            }
            release(connection,preparedStatement,resultSet);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return arrayList;
    }
//    2025/3/18 学习内容
    /**
     * 以键值对的形式（HashMap）返回一条信息
     * @param sql
     * @param parameters
     * @return
     */
    public static Map<String, Object>  queryMap(String sql,Object...parameters){
        HashMap<String, Object> stringObjectHashMap = null;
        try {
            stringObjectHashMap = null;
            Connection conn = getConn();
            PreparedStatement preparedStatement = getPreparedStatement(conn,sql, parameters);
            ResultSet resultSet = preparedStatement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int count = metaData.getColumnCount();
            resultSet.next();
            stringObjectHashMap = new HashMap<>();
            for (int i = 1; i <= count; i++) {
//                这里键是从元数据中拿到列的名字，值是从结果集中拿到的
                stringObjectHashMap.put(metaData.getColumnName(i),resultSet.getObject(i));
            }
            release(conn,preparedStatement,resultSet);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return stringObjectHashMap;
    }

    /**
     * 将信息封装成一个HashMap，然后用集合的方式存储
     * @param sql
     * @param parameters
     * @return
     */
    public static ArrayList<Map> queryMapList(String sql,Object...parameters){
        ArrayList<Map> maps = null;
        try {
            maps = new ArrayList<>();
            Connection conn = getConn();
            PreparedStatement preparedStatement = getPreparedStatement(conn,sql, parameters);
            ResultSet resultSet = preparedStatement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int count = metaData.getColumnCount();
            while(resultSet.next()) {
                HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                for (int i = 1; i <= count; i++) {
                    stringObjectHashMap.put(metaData.getColumnName(i), resultSet.getObject(i));
                }
                maps.add(stringObjectHashMap);
            }
            release(conn,preparedStatement,resultSet);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return maps;
    }

    /**
     * 将信息存储在数组中，一个数组就是一条信息
     * @param sql
     * @param parameters
     * @return
     */
    public static Object[] queryArray(String sql,Object...parameters){
        Object[] objects = new Object[0];
        try {
            Connection conn = getConn();
            PreparedStatement preparedStatement = getPreparedStatement(conn,sql,parameters);
            ResultSet resultSet = preparedStatement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int count = metaData.getColumnCount();
            objects = new Object[count];
            resultSet.next();
            for (int i = 0; i < count; i++) {
                objects[i]=resultSet.getString(i+1);
            }
            release(conn,preparedStatement,resultSet);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return objects;
    }

    /**
     * 将信息封装在数组中，然后以集合的方式存储
     * @param sql
     * @param parameters
     * @return
     */
    public static ArrayList<Object[]> queryArrList (String sql,Object...parameters){
        ArrayList<Object[]> list = null;
        try {
            list = new ArrayList<>();
            Connection conn = getConn();//这里不用这个了，getPreparedStatement方法中已经连接过了，我应该对其进行优化
            PreparedStatement preparedStatement = getPreparedStatement(conn,sql, parameters);
            ResultSet resultSet = preparedStatement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int count = metaData.getColumnCount();
            while(resultSet.next()) {
                Object[] objects = new Object[count];
                for (int i = 0; i < count; i++) {
                    objects[i] = resultSet.getString(i + 1);//从结果集中获取指定列的字符串值
                }

                list.add(objects);
            }
            release(conn,preparedStatement,resultSet);
            resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
//    我感觉resultSet结果集可以理解成游标指行，索引指列
}
